package com.fh.controller.system.login;

import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.service.me.SupplierUserService;
import com.fh.util.JsonResult;
import com.fh.util.MD5;
import com.fh.util.PageData;
import com.fh.util.SendEmailUtils;

/** 
 *
 * @author 王利慧
 * @datetime 2017-3-30 上午9:46:03 
 * @Description:注册页面
 */
@Controller
@RequestMapping(value ="/appregist")
public class RegistController extends BaseController{
	@Resource(name="supplierUserService")
	private SupplierUserService supplierUserService;
	/*
	 * 注册页面
	 */
	@RequestMapping(value="/toRegist")
	
	public String toRegister(){
	     
		  return "system/admin/registe";
	    }
	/**
	 * 发送验证码
	 * @return
	 */
	@RequestMapping(value="/sendCodes",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult sendCodes(String email){
		PageData pd = this.getPageData();
		pd.put("email", email);
		
		JsonResult result = new JsonResult();
		// 获取邮件主题
		String theme ="注册";
		// 生成五位随机验证码
		int vertifyCode = (int) (Math.random() * 100000);

		// 初始化邮件服务，传入参数收件人邮箱，验证的时候发
		SendEmailUtils seu = new SendEmailUtils(email, vertifyCode, theme);
		
		//判断邮箱是否存在
		try {
			PageData findU = supplierUserService.getUserByEmail(pd);
			if(findU!=null){//邮箱未注册
				result=JsonResult.error("300", "该邮箱已注册");
				return result;
			}else{
				//发送邮件
				seu.send();
			}
			
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		result = JsonResult.success();
		result.setData(vertifyCode);
		return result;
	}
	/**
	 * 确认注册 
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/sureRegiste",method=RequestMethod.POST)
	@ResponseBody
	public JsonResult sureRegisters(String email,String vertifyCode,Model model,String password) throws Exception{
		JsonResult json = new JsonResult();
		model.addAttribute("email", email);
		model.addAttribute("password",password);
		model.addAttribute("code", vertifyCode);
		PageData pd=new PageData();
		pd.put("email", email);
		pd.put("id", UUID.randomUUID().toString());
		 pd.put("password", MD5.md5(password));
		if(email!=null){
			PageData findU = supplierUserService.getUserByEmail(pd);
			if(findU!=null){
				json=JsonResult.error("300", "该邮箱已注册,请换一个邮箱");
				return json;
			}else{
				
				int re=supplierUserService.addUser(pd);
				int result=supplierUserService.addSupplier(pd);
				json = JsonResult.success();
				json.setData(re);
			}
		}
		return json;
	}
	
	
	
}
